package cn.cs.controller;

import cn.cs.common.*;
import cn.cs.pojo.ClientRepRel;
import cn.cs.pojo.ClientUser;
import cn.cs.service.ClientUserService;
import cn.cs.service.CsLoginService;
import cn.cs.service.RepairUserService;
import cn.cs.service.UserCompanyService;
import cn.cs.vo.TokenVO;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户注册控制器
 */
@Controller
@RequestMapping(value = "/clientUser")
public class ClientUserController {

    @Resource
    private CsLoginService csLoginService;
    @Resource
    private LogUtils logUtils;
    @Resource
    private RedisUtils redisUtils;
    @Resource
    private ClientUserService clientUserService;
    @Resource
    private CommonRpc commonRpc;
    @Resource
    private TokenUtils tokenUtils;
    @Resource
    private RepairUserService repairUserService;

    @Resource
    private UserCompanyService userCompanyService;



    /**
     * 发送短信
     *
     * @param phone
     * @return
     */
    @RequestMapping(value = "/p/sendSMS")
    @ResponseBody
    public Dto sendSMS(String phone) {
        if(redisUtils.exist(phone)){
            redisUtils.delete(phone);
        }
        String code = commonRpc.sendBatchSms(phone);
        redisUtils.set(phone,120,code);
        return DtoUtil.returnSuccess("短信发送成功", code);
    }


    /**
     * 绑定手机号
     *
     * @param phone
     * @return
     * @throws Exception
     */
    @RequestMapping(path = "/p/bindPhone")
    @ResponseBody
    public Dto bindPhone(String openId, String phone, String code) throws Exception {
        String _code = redisUtils.get(phone).toString();
        if (!EmptyUtils.isEmpty(_code)) {
            if (code.equals(_code)) {
        ClientUser clientUser = clientUserService.getClientUserByPhone(phone);
        if(EmptyUtils.isNotEmpty(clientUser) && !openId.equals(clientUser.getOpenId())){
            return DtoUtil.returnFail("手机号已存在，请更换手机号", "003");
        }
        ClientUser user = clientUserService.getClientUserByOpenIdAccountNull(openId);
        user.setPhone(phone);
        int i = clientUserService.modifyClientUserByOpenId(user);
        String token = tokenUtils.generateToken("unknown", user);
        tokenUtils.save(token, user);
        redisUtils.delete(phone);
        return DtoUtil.returnSuccess("绑定手机号成功", token);
            } else {
                return DtoUtil.returnFail("验证码错误，请重新输入", "001");
            }
        } else {
            return DtoUtil.returnFail("验证码失效，请重新获取", "002");
        }
    }

    /**
     * 账号密码登陆
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(path = "/p/loginByAccount")
    @ResponseBody
    public Dto loginByAccount(String openId, String user_account, String user_password) throws Exception {
        ClientUser user = clientUserService.getClientUserByAccount(user_account);
        if (!EmptyUtils.isEmpty(user)) {
            if("0".equals(user.getValidState())){
                return DtoUtil.returnFail("账户被锁定，无法登陆", "003");
            }
            if (user.getUserPassword().equals(MD5Util.encode(user_password))) {
                user.setOpenId(openId);
                clientUserService.modifyClientUser(user);
                String token = tokenUtils.generateToken("unknown", user);
                tokenUtils.save(token, user);
                return DtoUtil.returnSuccess("登陆成功", token);
            } else {
                return DtoUtil.returnFail("密码错误，请重新输入", "001");
            }
        } else {
            return DtoUtil.returnFail("账号不存在", "002");
        }
    }

    /**
     * 置换token
     *
     * @param token 旧的token
     * @return 新token，TokenVO格式
     * @throws Exception 未登录异常
     */
    @RequestMapping(value = "/p/replaceToken")
    @ResponseBody
    public Dto replaceToken(@RequestHeader String token) throws Exception {
        return DtoUtil.returnSuccess("置换成功", tokenUtils.replaceTokenClientUser("unknown", token));
    }

    /**
     * 根据openId查询clientUser
     * @param openId
     * @return
     * @throws Exception
     */
    @RequestMapping("/wxApi/getClientUserByOpenId")
    @ResponseBody
    public Dto<ClientUser> getClientUserByOpenId(String openId) throws Exception {
        ClientUser clientUser = clientUserService.getClientUserByOpenId(openId);
        if (EmptyUtils.isEmpty(clientUser)) {
            return DtoUtil.returnFail("不存在", "0001");
        }
        return DtoUtil.returnSuccess("已存在", clientUser);
    }


    /**
     * 添加我的维修工
     * @param userId
     * @param repUserId
     * @return
     * @throws Exception
     */
    @RequestMapping("/wxApi/addRepairUser")
    @ResponseBody
    public Dto getRepairUserInfoById(String userId, String repUserId) throws Exception {
        String createTime = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
        Map<String, Object> map = repairUserService.getRepairUserByUserId(userId);
        ClientRepRel clientRepRel = new ClientRepRel();
        clientRepRel.setClientUserId(userId);
        clientRepRel.setRepUserId(repUserId);
        if (map == null) {
            String id = IdWorker.getId();
            clientRepRel.setId(id);
            clientRepRel.setCreateTime(createTime);
            clientUserService.itriptxAddClientRepRel(clientRepRel);
        } else {
            clientRepRel.setId(map.get("crId").toString());
            clientRepRel.setUpdateTime(createTime);
            clientUserService.updateClientRepRel(clientRepRel);
        }
        return DtoUtil.returnSuccess("操作成功");
    }

    /**
     * 获取私人维修工
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/wxApi/getloveCountAndOrderCount")
    @ResponseBody
    public Dto getRepairUserInfo(HttpServletRequest request) throws Exception {
        return repairUserService.getRepairUserByUserId(request);
    }

    /**
     * 获取用户信息
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("/wxApi/getUser")
    @ResponseBody
    public Dto getUser(String userId) throws Exception {
        if(EmptyUtils.isEmpty(userId)){
            return DtoUtil.returnFail("用户不存在，请重新授权登陆", "userNull001");
        }
        return DtoUtil.returnSuccess("操作成功", clientUserService.getClientUserById(userId));
    }

    /**
     * 分页查询 普通用户信息
     *
     * @param pageNumber
     * @param pageSize
     * @return
     * @throws Exception TODO 添加搜索
     */
    @RequestMapping(value = "/csPlatform/getClientUserByPage")
    public Dto getClientUserByPage(Integer pageNumber, Integer pageSize, String phone) throws Exception {
        Map<String, Object> param = new HashMap<>();
        param.put("phone", phone);
        return DtoUtil.returnSuccess("获取成功", clientUserService.queryClientUserPageByMap(param, pageNumber, pageSize));
    }

    /**
     * 查询用户公司信息
     * @param pageNumber
     * @param pageSize
     * @param userId
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/wxApi/getUserCompanyByPage")
    public Dto getUserCompanyByPage(Integer pageNumber, Integer pageSize, String userId) throws Exception {
        if(EmptyUtils.isEmpty(userId)){
            userId = "0000000";
        }
        Map<String, Object> param = new HashMap<>();
        param.put("userId", userId);
        return DtoUtil.returnSuccess("获取成功", userCompanyService.queryUserCompanyPageByMap(param, pageNumber, pageSize));
    }

    /**
     * 获取微信版本号
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("/getWxVersionCode")
    @ResponseBody
    public Dto getWxVersionCode() throws Exception {
        return DtoUtil.returnSuccess("获取成功", clientUserService.getWxVersionCode());
    }

    /**
     * 修改微信版本号
     * @return
     * @throws Exception
     */
    @RequestMapping("/setWxVersionCode")
    @ResponseBody
    public Dto setWxVersionCode(String versionCode) throws Exception {
        return DtoUtil.returnSuccess("操作成功", clientUserService.setWxVersionCode(versionCode));
    }

    /**
     * 根据维修工获取用户列表
     * @param rep_user_id
     * @return
     * @throws Exception
     */
    @RequestMapping("/wxApi/getUserByRepUserId")
    @ResponseBody
    public Dto getUserByRepUserId(String rep_user_id) throws Exception {
        return DtoUtil.returnSuccess("操作成功", clientUserService.getUserByRepUserId(rep_user_id));
    }


    /**
     * 修改用户信用分
     *
     * @param id,
     * @param creditScore
     * @param type 分类 1增加 0扣除
     * @param remarks 备注说明
     * @return
     * @throws Exception TODO 添加搜索
     */
    @RequestMapping(value = "/csPlatform/updateUserScore")
    public Dto updateUserScore(String id, String creditScore, String type, String remarks) throws Exception {
        ClientUser user = clientUserService.getClientUserById(id);
        int score = Integer.valueOf(user.getCreditScore());
        if("1".equals(type)){
            score = score + Integer.valueOf(creditScore);
        }else{
            score = score - Integer.valueOf(creditScore);
        }
        user.setId(id);
        user.setCreditScore(String.valueOf(score));
        Map<String, Object> map = new HashMap<>();
        map.put("userId", id);
        map.put("type", type);
        map.put("score", creditScore);
        map.put("newScore", user.getCreditScore());
        map.put("remarks", remarks);
        clientUserService.saveUserScoreHistory(map);
        return DtoUtil.returnSuccess("操作成功", clientUserService.modifyClientUser(user));
    }

    /**
     * 查询用户信用分明细
     *
     * @param id,
     * @return
     */
    @RequestMapping(value = "/csPlatform/getUserScoreHistoryByUserId")
    public Dto getUserScoreHistoryByUserId(String id) throws Exception {
        return DtoUtil.returnSuccess("获取成功", clientUserService.getUserScoreHistoryByUserId(id));
    }



    /**
     * 置换token
     *
     * @param token 旧的token
     * @return 新token，TokenVO格式
     * @throws Exception 未登录异常
     */
    @RequestMapping(value = "/p/replaceTokenOut", method = RequestMethod.POST)
    @ResponseBody
    public Dto replaceTokenOut(@RequestHeader String token) throws Exception {
        TokenVO tokenVO = new TokenVO(csLoginService.replace(token), Constants.Redis_Expire.SESSION_TIMEOUT, new Date().getTime());
        return DtoUtil.returnSuccess("置换成功", tokenVO);
    }

    /**
     * 根据token加载当前登录用户
     *
     * @param token
     * @return DmUserVO格式的用户信息
     * @throws Exception 未登录异常
     */
    @RequestMapping(value = "/v/loadCurrentUserByToken", method = RequestMethod.POST, produces = {"application/json"})
    @ResponseBody
    public Dto loadCurrentUserByToken(@RequestHeader String token) throws Exception {
        return DtoUtil.returnSuccess("查询成功", csLoginService.loadCurrentUserByTokenAsCsUserVo(token));
    }

}